<template>
    <div class="container">
        <van-sticky>
            <div class="head">
                <img class="head-back-img" @click="goBack" src="../assets/back.svg" alt="">
                <div class="title">影片详情</div>
            </div>
        </van-sticky>
        <div class="header">
            <div class="card-content">
                <div class="left">
                    <!-- 电影海报 -->
                    <div class="poster-wrapper">
                        <img :src="$buildFullImageUrl + film_infos.pic" alt="电影海报" class="movie-poster">
                    </div>
                    <!-- 电影信息区域 -->
                    <div class="movie-info">
                        <div class="movie-title">{{ film_infos.film_name }}</div>
                        <!-- 信息 -->
                        <div class="rating-bar">
                            {{ film_infos.film_type }}/{{ film_infos.duration }}分钟
                        </div>
                        <div class="rating-bar">
                            {{ film_infos.publish_date }} {{ film_infos.movie_area }}
                        </div>
                        <div class="rating-bar">
                            主演：{{ film_infos.cast }}
                        </div>
                        <!-- 简介标签 -->
                        <div class="intro-tag">
                            <div>{{ film_infos.like }}</div>
                            <div>人想看</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="title">简介</div>
        <div>
            <van-collapse :border="false" v-model="activeNames">
                <van-collapse-item name="2">
                    <template #title>
                        <span v-if="film_infos.intro && activeNames.length === 0">{{ film_infos.intro.substring(0, 50)
                            }}...</span>
                        <span v-if="film_infos.intro && activeNames[0] === '2'">{{ film_infos.intro }}</span>
                    </template>
                </van-collapse-item>
            </van-collapse>
        </div>
        <div class="title">选择影院</div>
        <div class="selectMovie">
            <van-tabs v-model="activeTab" animated class="selectdate">
                <van-tab v-for="(date, index) in dateList" :key="index">
                    <template #title>
                        <div class="custom-tab">
                            <div class="date-name">{{ date.dateName }}</div>
                            <div class="date-value">{{ date.dateValue }}</div>
                        </div>
                    </template>
                </van-tab>
            </van-tabs>
            <div style="margin-top: 10px;">
                <van-dropdown-menu>
                    <!--                    <van-dropdown-item class="selNone" v-model="value1" :options="option1">-->
                    <!--                        &lt;!&ndash;                        <van-tree-select :items="cityItems" :active-id.sync="activeId" @click-item="onClickItem"&ndash;&gt;-->
                    <!--                        &lt;!&ndash;                            @click-nav="onClickNav" :main-active-index.sync="activeIndex" />&ndash;&gt;-->
                    <!--                        <div class="area">-->
                    <!--                            <div v-for="(item, index) in areaList" @click="onClickItem(item)">-->
                    <!--                                <div>{{ item.region_name }}</div>-->
                    <!--                                <van-icon size="18" v-if="item.region_id === region_id" color="#ee0a24"-->
                    <!--                                    name="success" />-->
                    <!--                            </div>-->
                    <!--                        </div>-->
                    <!--                    </van-dropdown-item>-->
                    <van-dropdown-item class="selNone" v-model="value1" :options="option1" @change="onClickItem" />
                    <van-dropdown-item class="selNone" v-model="value2" :options="option2" @change="changeValue2" />
                    <van-dropdown-item class="selNone" v-model="value3" :options="option3" @change="changeValue3" />
                </van-dropdown-menu>
            </div>
            <div class="movieContent">
                <!-- @load="getData" -->
                <van-list v-model="loading" :finished="finished" finished-text="没有更多电影院了" class="movie-list">
                    <van-cell @click="goSelectTime(item)" v-for="(item, index) in movies" :key="index"
                        class="movie-card">
                        <div class="movieInfo">
                            <div class="name">{{ item.cinema_name }}</div>
                        </div>
                        <div class="movieInfo">
                            <div class="address">{{ item.address }}</div>
                            <div class="instance">{{ item.instance }}km</div>
                        </div>
                        <div class="movieInfo" v-if="item.phone">
                            <div class="phone">影院电话：{{ item.phone }}</div>
                        </div>
                        <!--                        <div class="movieInfo">-->
                        <!--                            <div class="is_refund" v-if="item.is_refund == 1">退</div>-->
                        <!--                        </div>-->
                        <div class=" is_refund">
                            <div :style="{ color: x.color, borderColor: x.color }" v-for="(x, y) in item.tagList">{{
                                x.text }}
                            </div>
                        </div>
                    </van-cell>
                </van-list>
            </div>
        </div>
    </div>
</template>
<script>
import plantAPI from "@/api/plant";
import { getDistance } from 'geolib';
export default {
    data() {
        return {
            isReleased: false,
            movies: [],
            moviesCopy: [],
            loading: false,
            finished: false,
            page: 1,
            value1: 'a',
            value2: 'a',
            value3: 'c',
            option1: [
                { text: '城市', value: 'a' }
            ],
            option3: [
                { text: '退票', value: 'c' },
                { text: '可退票', value: 'a' },
                { text: '不可退', value: 'b' },
            ],
            option2: [
                { text: '距离', value: 'a' },
                { text: '由近到远', value: 'b' }
            ],
            cityItems: [],
            activeId: 1,
            activeIndex: 0,
            cityId: '',
            cityName: '',
            region_id: '',
            areaList: [],
            activeTab: 0,
            dateList: [],
            activeNames: [],
            film_infos: {},

            isDataLoaded: false, // 数据加载状态
        }
    },
    created() {
        this.cityName = localStorage.getItem("cityName");
        this.cityId = localStorage.getItem("city_id");
        let status = this.$route.query.status
        this.activeName = status ? status == 1 ? 'hot' : 'soon' : 'fileName'
        // this.generateDateList();
        this.getmovieTheater()
        this.getFilm_info()


        plantAPI.getregionAPI(this.cityId).then(res => {
            this.areaList = JSON.parse(res.data.body).data;
            const option = []
            this.areaList.forEach(item => {
                option.push({
                    text: item.region_name,
                    value: item.region_id
                })
            })
            option.unshift({
                text: '区域', value: 'a'
            })
            this.option1 = [...option]
        })
    },
    watch: {
        region_id: {
            immediate: true,
            handler(newVal) {
                if (newVal && this.isDataLoaded) {
                    this.getregionData('region');
                }
            }
        },
        value2: {
            immediate: true,
            handler(newVal) {
                if (newVal && this.isDataLoaded) {
                    this.getregionData('instance');
                }
            }
        },
        value3: {
            immediate: true,
            handler(newVal) {
                if (newVal && this.isDataLoaded) {
                    this.getregionData('ticket');
                }
            }
        },

    },
    methods: {
        changeValue2(value) {
            this.value2 = value
        },
        changeValue3(value) {
            this.value3 = value
        },
        onClickItem(value) {
            // this.region_id = data.id
            // this.option1[0].text = data.text;
            // this.value1 = 'a';
            // this.region_id = data.region_id
            // this.option1[0].text = data.region_name;
            // this.value1 = 'a';
            this.region_id = value
            this.value1 = value;
        },
        // onClickNav(index) {
        //     plantAPI.getregionAPI(this.cityList[index].city_id).then(res => {
        //         this.cityList[index].children = JSON.parse(res.data.body).data;
        //         this.cityItems = [];
        //         this.cityList.map((item) => {
        //             let child = []
        //             if (item.children) {
        //                 item.children.map(i => {
        //                     child.push({
        //                         text: i.region_name,
        //                         id: i.region_id
        //                     })
        //                 })
        //             }
        //
        //             let obj = {
        //                 text: item.city_name,
        //                 children: child
        //             }
        //             this.cityItems.push(obj)
        //         })
        //     })
        // },

        goBack() {
            this.$router.go(-1)
        },
        goSelectTime(item) {

            const selectedDate = this.dateList[this.activeTab];
            this.$router.push({
                path: './comingTheater/movies',
                query: {
                    selected_date: selectedDate.fullDateValue, // 格式: "2025-08-02"
                    film_Info: JSON.stringify(item),
                    fims_id: this.$route.query.film_id
                }
            })
        },

        getFilm_info() {
            plantAPI.gethotAPI().then(res => {
                this.film_infos = JSON.parse(res.data.body).data.records.find(item => item.film_id == this.$route.query.film_id)
                console.log(this.film_infos, 'this.film_infos')
                const now = Date.now(); // 获取当前时间戳（毫秒）
                this.isReleased = new Date(this.film_infos.publish_date).getTime() < now;
                this.generateDateList();

            })
        },
        calculate(lon1, lat1) {
            let lon2 = localStorage.getItem('longitude')
            let lat2 = localStorage.getItem('latitude')
            if (lat1 && lon1 && lat2 && lon2) {
                const distanceInMeters = getDistance(
                    { latitude: parseFloat(lat1), longitude: parseFloat(lon1) },
                    { latitude: parseFloat(lat2), longitude: parseFloat(lon2) }
                );
                return (distanceInMeters / 1000).toFixed(2)
            }
        },
        async getmovieTheater() {
            this.loading = true;
            this.finished = false;
            try {
                const res = await plantAPI.getcinemaAPI(this.cityId);
                const data = JSON.parse(res.data.body).data;

                const tag = ['3D眼镜免费', '休息区', '改签', '艺术影厅', '可刷卡', '可停车', 'VIP厅'];
                this.moviesCopy = data.map(item => {
                    item.instance = this.calculate(item.longitude, item.latitude);
                    const service = JSON.parse(item.service);
                    let tagList = [];
                    if (service) {
                        Object.keys(service).forEach((key) => {
                            if (tag.includes(key)) {
                                tagList.push({
                                    text: key,
                                    color: (key === '改签' || key === '艺术影厅' || key === 'VIP厅')
                                        ? "rgb(95, 224, 95)"
                                        : "#FFB433"
                                });
                            }
                        });
                    }
                    if (item.is_refund === 1) {
                        tagList.unshift({
                            text: '退',
                            color: "rgb(95, 224, 95)"
                        });
                    }
                    return {
                        ...item,
                        tagList
                    };
                });
                this.moviesCopy = [...this.moviesCopy].sort((a, b) => a.instance - b.instance)
                this.movies = [...this.moviesCopy];
                this.isDataLoaded = true;

                // 更新列表状态
                this.loading = false;
                this.finished = true;

                // 应用筛选条件
                if (this.region_id) this.getregionData('region');
                if (this.value2) this.getregionData('instance');
                if (this.value3) this.getregionData('ticket');

            } catch (err) {
                this.loading = false;
                this.finished = true;
            }
        },
        getregionData(status) {
            if (!this.isDataLoaded) return;
            this.loading = true;
            switch (status) {
                case 'region':
                    if (this.region_id === 'a') {
                        this.movies = [...this.moviesCopy];
                    } else {
                        this.movies = this.moviesCopy.filter(item => item.region_id == this.region_id);
                    }

                    break;

                case 'instance':
                    this.movies = (this.value2 == 'b')
                        ? [...this.moviesCopy].sort((a, b) => a.instance - b.instance)
                        : [...this.moviesCopy];
                    break;

                case 'ticket':
                    if (this.value3 == 'a') {
                        this.movies = this.moviesCopy.filter(item => item.is_refund == 1);
                    } else if (this.value3 == 'b') {
                        this.movies = this.moviesCopy.filter(item => item.is_refund != 1);
                    } else {
                        this.movies = [...this.moviesCopy];
                    }
                    break;

                default:
                    this.movies = [...this.moviesCopy];
            }

            this.loading = false;
            this.finished = true;
        },


        generateDateList() {
            const dateList = [];
            // 根据发布状态选择起始日期：已上映用今天，未上映用发布日期
            const startDate = this.isReleased ? new Date() : new Date(this.film_infos.publish_date);
            const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

            for (let i = 0; i < 7; i++) {
                const currentDate = new Date(startDate);
                currentDate.setDate(startDate.getDate() + i);

                // 以下原有逻辑保持不变...
                let dateName = '';
                if (i === 0) {
                    dateName = this.isReleased ? '今天' : '首映';
                } else if (i === 1) {
                    dateName = this.isReleased ? '明天' : '首映+1';
                } else if (i === 2 && this.isReleased) {
                    dateName = '后天';
                } else {
                    dateName = weekDays[currentDate.getDay()];
                }

                const year = currentDate.getFullYear();
                const month = currentDate.getMonth() + 1;
                const day = currentDate.getDate();
                const dateValue = `${month}月${day}日`;
                const months = String(month).padStart(2, '0');
                const days = String(day).padStart(2, '0');
                const fullDateValue = `${year}-${months}-${days}`;

                dateList.push({
                    dateName,
                    dateValue,
                    fullDate: currentDate,
                    fullDateValue
                });
            }

            this.dateList = dateList;
        },

    }
}
</script>
<style lang="scss" scoped>
/* 全局样式（不受 scoped 限制） */
:global {

    html,
    body {
        background-color: #F5F6F8 !important;
        margin: 0;
        padding: 0;
        height: 100%;
    }
}

::v-deep .van-popup {
    max-height: 300px;
}

.selNone {
    width: 351px;
    margin: auto;

    //::v-deep .van-dropdown-item__option {
    //    display: none;
    //}

    ::v-deep .van-dropdown-item {
        width: 351px;
        left: calc(50% - 175px);
    }

    .area {
        width: 100%;
        height: 200px;
        background: #FFFFFF;
        overflow-y: auto;

        >div {
            width: 100%;
            border-bottom: 1px solid #d7d5d5;
            display: flex;
            justify-content: space-between;
            padding: 10px 20px 10px 20px;
            box-sizing: border-box;

            >div:nth-child(1) {
                width: calc(100% - 50px);
                color: #424242;
                font-size: 14px;
                text-align: left;
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
            }
        }
    }
}

.container {
    background: #F5F6F8;
    min-height: calc(100vh - 55px);
    /* 确保容器撑满整个视口 */
    padding-bottom: 55px;
}

::v-deep .van-sticky {
    background: #ffffff;

}

/* 自定义样式 */
.tab-container {
    padding: 10px;
}

.custom-tab {
    min-width: 60px;
    text-align: center;
}

.date-name {
    font-size: 14px;
    margin-bottom: 4px;
    color: #1d2129;
    font-weight: 500;
}

.date-value {
    font-size: 12px;
    color: #86909c;
    position: relative;
}

/* 选中状态样式 */
.van-tab--active .date-name,
.van-tab--active .date-value {
    color: #f53f3f;
    /* 红色选中状态 */
}

.van-tabs__line {
    bottom: 0.6px;
}

.van-tab--active .date-value::after {
    content: '';
    position: absolute;
    bottom: -4px;
    left: 50%;
    transform: translateX(-50%);
    width: 16px;
    height: 2px;
    background-color: #f53f3f;
    border-radius: 1px;
}

/* 隐藏Vant默认下划线 */
.van-tabs__line {
    display: none !important;
}

.van-collapse {
    width: 351px;
    background: #FFFFFF;
    border-radius: 10px !important;
    margin: auto;
    overflow: hidden;

    /* 确保圆角生效 */
    ::v-deep .van-collapse-item__title--expanded::after {
        display: none;
    }

    ::v-deep .van-collapse-item__wrapper {
        display: none;
    }
}

.title {
    margin: 10px 24px;
    height: 21px;
    font-family: PingFang SC;
    font-weight: 600;
    font-size: 15px;
    color: #1A1A1A;
}


.selectMovie {
    width: 351px;
    margin: auto;
    background: #FFFFFF;
    border-radius: 10px;

    .selectdate {
        padding-top: 10px;
    }

    .movieContent {
        margin-top: 5px;
        color: #999999;

        .phone,
        .instance {
            color: #999999;
            font-size: 12px;
            font-family: PingFang SC;
        }

        .is_refund {
            margin-top: 2px;
            color: rgb(12, 212, 12);
            text-align: center;
            line-height: 18px;
            font-size: 12px;
            height: 18px;
            width: 18px;
            //border: 1px solid rgb(12, 212, 12);
        }

        .movieInfo {
            display: flex;
            justify-content: space-between;
            padding: 0 9px;
            // margin-top: 2px;

            .address {
                font-family: PingFang SC;
                font-size: 12px;
                color: #999999;
                flex-wrap: nowrap;
                margin-right: 10px;
                width: 300px;
                white-space: nowrap; // 禁止换行
                overflow: hidden; // 隐藏溢出内容
                text-overflow: ellipsis; // 显示省略号
                display: inline-block; // 必须设置为块级元素才能生效
            }

            .time {
                color: #666;
            }

            .name {
                font-family: PingFang SC;
                font-weight: 600;
                font-size: 14px;
                color: #1A1A1A;
            }
        }

        .is_refund {
            width: 100%;
            display: flex;
            flex-wrap: wrap;
            margin-top: 4px;
            padding: 0 9px;
            box-sizing: border-box;

            >div {
                //display: flex;
                padding: 2px 3px 0 3px;
                //height: 20px;
                border-radius: 2px;
                line-height: 12px;
                height: 12px;
                font-size: 8px;
                border: 1px solid #000;
                margin-right: 5px;
            }
        }
    }
}


.head {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    position: relative; // 关键：设置相对定位
    background-color: #ffffff;

    .head-back-img {
        width: 20px;
        height: 20px;
        position: absolute;
        left: 15px;
    }

    .title {
        width: 100%;
        text-align: center;
        font-size: 16px;
        color: #000000;
    }
}


.header {
    width: 351px;
    height: 146px;
    border-radius: 10px;
    margin: auto;
    background: linear-gradient(to top left, rgba(255, 255, 255, 0.3) 75%, rgba(238, 71, 59, 0.3) 100%);
    box-shadow: 0rpx 0rpx 12rpx rgba(0, 0, 0, 0.16);
}

.card-content,
.left {
    display: flex;
    align-items: center;
    width: 97%;
    justify-content: space-between;
    // background: #fff;
    padding: 6px;
    padding-right: 12px;
    border-radius: 10px;

    .poster-wrapper {
        width: 96px;
        height: 124px;

        .movie-poster {
            width: 96px;
            height: 124px;
            border-radius: 10px;
        }

    }

    .movie-info {
        margin-left: 16px;
        flex: 1; // Add this to make it take remaining space
        min-width: 0; // Important for flex children to allow text overflow

        .intro-tag {
            display: inline-flex; // 改为 inline-flex 让宽度自适应内容
            align-items: center;
            text-align: center;
            min-width: 90px;
            height: 21px;
            background: #F4F4F4;
            line-height: 21px;
            border-radius: 3px;
            margin-top: 10px;

            >div:first-child {
                font-family: PingFang SC;
                font-weight: 600;
                font-size: 12px;
                color: #EE473B;
                margin-left: 10px;
            }

            >div:last-child {
                margin-left: 6px;
                font-family: PingFang SC;
                font-size: 10px;
                color: #575757;
                margin-right: 10px;
            }
        }

        .rating-bar {
            display: block; // Change from flex to block for better text overflow
            position: relative;
            margin-top: 5px;
            height: 14px;
            font-family: PingFang SC;
            font-size: 10px;
            color: #575757;
            width: 100%;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            padding: 0;
        }

        .types {
            display: flex;
            align-items: center;
            position: relative;

            .type1 {
                position: absolute;
                left: 0;
                top: 0;
                width: 21px;
                height: 16px;
                background: #EE473B;
                border-radius: 5px 0px 0px 5px;
                font-family: PingFang SC;
                font-size: 10px;
                color: #FFFFFF;
                line-height: 16px;
                text-align: center;
                border: 1px solid #EE473B;
            }

            .type2 {
                position: absolute;
                left: 20px;
                text-align: center;
                top: 0;
                width: 29px;
                height: 16px;
                line-height: 16px;
                border-radius: 0px 5px 5px 0px;
                border: 1px solid #EE473B;
                font-size: 10px;
                color: #EE473B;
            }
        }

        .movie-title {

            height: 28px;
            font-family: PingFang SC;
            font-weight: 500;
            font-size: 20px;
            color: #1A1A1A;
        }


    }
}
</style>
